package com.lin.blog.service.impl;

import com.lin.blog.service.IQiNiuService;
import com.lin.constant.ResultCode;
import com.lin.utils.Result;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import io.netty.handler.codec.http2.Http2CodecUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @program: blog
 * @description: 七牛云 服务层
 * @author: Lin
 * @create: 2020-04-29 15:30
 **/
@Service
public class QiNiuServiceImpl implements IQiNiuService, InitializingBean {

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    /**
     * 定义七牛云上传的相关策略
     */
    private StringMap putPolicy;


    /**
     *  上传文件
     * @param file
     * @return
     * @throws QiniuException
     */
    @Override
    public Result uploadFile(MultipartFile multipartFile) throws IOException {

        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        // ，防止生成的临时文件重复
        final File uploadFile = File.createTempFile(fileName, prefix);
        // MultipartFile to File
        multipartFile.transferTo(uploadFile);


        Response response = this.uploadManager.put(uploadFile, fileName, getUploadToken());
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(uploadFile, fileName, getUploadToken());
            retry++;
        }

        //程序结束时，删除临时文件
        deleteFile(uploadFile);

        if (response.statusCode == 200) {
            return Result.success("http://" + domain + "/" + fileName);
        }
        return Result.failure(ResultCode.FILE_UPLOAD_FAILED);
    }

    @Override
    public Result getToken() {
        return Result.success(getUploadToken());
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }
    /**
     * 获取上传凭证
     */
    private String getUploadToken() {
        return this.auth.uploadToken(bucket, null, 3600, putPolicy);
    }


    /**
     * 删除
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

}
